<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.name" clearable placeholder="search name" style="width: 200px" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="550px">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="150px">
        <el-form-item label="name" prop="name">
          <el-select v-model="form.name" style="width: 100%">
            <el-option v-for="item in productList" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <template v-if="['banner', 'rupesProduct', 'devilbissProduct', 'about'].includes(form.name)">
          <el-form-item label="image" prop="imgName">
            <el-upload class="uploadImg" style="width: 100%" ref="upload" :limit="1" :auto-upload="true" :before-upload="beforeUpload" :headers="headers" :on-success="handleSuccess" :on-remove="removeFile1" :on-error="handleError" :on-exceed="handleExceed" :file-list="fileList" :action="fileUploadApi + '?name=' + form.name">
              <div class="eladmin-upload"><i class="el-icon-upload" /> Add Picture</div>
              <div slot="tip" class="el-upload__tip">upload img,jpeg,jpg...</div>
            </el-upload>
          </el-form-item>
        </template>
        <template v-if="form.name === 'banner'">
          <el-form-item label="detail" prop="detail">
            <el-input v-model="form.detail" style="width: 100%" />
          </el-form-item>
        </template>
        <template v-if="['rupesProduct', 'devilbissProduct'].includes(form.name)">
          <el-form-item label="productName" prop="detail">
            <el-input v-model="form.detail" style="width: 100%" />
          </el-form-item>
          <el-form-item label="productNameDetail" prop="productNameDetail">
            <el-input v-model="form.productNameDetail" style="width: 100%" />
          </el-form-item>
          <el-form-item label="Product Features" prop="productFeatures">
            <el-input type="textarea" :rows="2" v-model="form.productFeatures" style="width: 100%" />
          </el-form-item>
          <el-form-item label="Main Images" prop="mainImages">
            <el-upload class="uploadImg" ref="upload" :auto-upload="true" :before-upload="beforeUpload" :headers="headers" :on-success="handleSuccess2" :on-remove="removeFile2" :on-error="handleError" :file-list="fileList2" :action="fileUploadApi + '?name=' + form.name">
              <div class="eladmin-upload"><i class="el-icon-upload" /> Add Picture</div>
              <div slot="tip" class="el-upload__tip">upload img,jpeg,jpg...</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="Detail Images" prop="detailImages">
            <el-upload class="uploadImg" ref="upload" :auto-upload="true" :before-upload="beforeUpload" :headers="headers" :on-success="handleSuccess3" :on-remove="removeFile3" :on-error="handleError" :file-list="fileList3" :action="fileUploadApi + '?name=' + form.name">
              <div class="eladmin-upload"><i class="el-icon-upload" /> Add Picture</div>
              <div slot="tip" class="el-upload__tip">upload img,jpeg,jpg...</div>
            </el-upload>
          </el-form-item>
        </template>
        <!-- <el-form-item label="remark" prop="remark">
          <el-input v-model="form.remark" style="width: 100%" />
        </el-form-item>  -->
        <template v-if="form.name === 'about'">
          <el-form-item label="introduce" prop="introduce">
            <el-input v-model="form.introduce" style="width: 100%" />
          </el-form-item>
          <el-form-item label="phone" prop="phone">
            <el-input v-model="form.phone" style="width: 100%" />
          </el-form-item>
          <el-form-item label="email" prop="email">
            <el-input v-model="form.email" style="width: 100%" />
          </el-form-item>
        </template>
        <template v-if="['rupesVideo', 'devilbissVideo'].includes(form.name)">
          <el-form-item label="videoUrl" prop="extrajson">
            <el-input v-model="form.extrajson" style="width: 100%" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">Cancle</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="submitOK">Ok</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%" @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="name" />
      <el-image :src="imgPath" fit="contain" lazy class="el-avatar">
        <div slot="error">
          <i class="el-icon-document" />
        </div>
      </el-image>
      <el-table-column prop="detail" label="detail" />
      <el-table-column prop="remark" label="remark" />
      <el-table-column prop="createTime" label="createTime" />
      <el-table-column v-if="checkPer(['admin', 'serverDeploy:edit', 'serverDeploy:del'])" label="operate" width="150px" align="center">
        <template slot-scope="scope">
          <udOperation :data="scope.row" :permission="permission" />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudServer from '@/api/product/product'
import { add } from '@/api/product/product'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, name: null, img: null, detail: null, remark: null }
export default {
  name: 'Server',
  components: { pagination, crudOperation, rrOperation, udOperation, DateRangePicker },
  cruds() {
    return CRUD({ title: 'product', url: 'api/product/list', crudMethod: { ...crudServer }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      productList: [{ name: 'banner' }, { name: 'rupesProduct' }, { name: 'devilbissProduct' }, { name: 'about' }, { name: 'rupesVideo' }, { name: 'devilbissVideo' }],
      fileList: [],
      fileList1: [],
      fileList2: [],
      fileList3: [],
      imgPath: '',
      delAllLoading: false,
      headers: { Authorization: getToken() },
      accountList: [],
      accountMap: {},
      loading: false,
      permission: {},
      rules: {
        name: [{ required: true, message: 'please input name', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['baseApi', 'fileUploadApi'])
  },
  methods: {
    add() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          add(this.form)
            .then((res) => {
              this.loading = false
              this.$notify({
                title: res ? '连接成功' : '连接失败',
                type: res ? 'success' : 'error',
                duration: 2500
              })
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    submitOK() {
      // extrajson
      if (this.form.name === 'about') {
        this.form.extrajson = JSON.stringify({
          introduce: this.form.introduce,
          phone: this.form.phone,
          email: this.form.email
        })
      }
    
      
      if (['rupesProduct', 'devilbissProduct'].includes(this.form.name)) {
        this.form.extrajson = JSON.stringify({
          productNameDetail: this.form.productNameDetail,
          productFeatures: this.form.productFeatures,
          mainImages: this.fileList2,
          detailImages: this.fileList3,
        })
      }
      console.log('好好好·', this.form);
      this.crud.submitCU()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      // this.form.name = file.name
      return isLt2M
    },
    // 在表单打开时设置文件列表
    [CRUD.HOOK.beforeToEdit](crud, form) {
      if (form.name === 'about') {
        try {
          const extrajson = JSON.parse(form.extrajson)
          this.form.introduce = extrajson.introduce
          this.form.phone = extrajson.phone
          this.form.email = extrajson.email
        } catch (error) {
          
        }
      }
      if (form.imgPath && form.imgName) {
        this.fileList = [
          {
            name: form.imgName,
            url: form.imgPath
          }
        ]
      } else {
        this.fileList = []
      }
      if (['rupesProduct', 'devilbissProduct'].includes(this.form.name)) {
        this.$set(this.form, 'productNameDetail', '')
        this.$set(this.form, 'productFeatures', '')
        try {
          const extrajson = JSON.parse(form.extrajson)
          this.form.productNameDetail = extrajson.productNameDetail
          this.form.productFeatures = extrajson.productFeatures
          this.fileList2 = extrajson.mainImages
          this.fileList3 = extrajson.detailImages
        } catch (error) {
          this.form.productNameDetail = ''
          this.form.productFeatures = ''
          this.fileList2 = []
          this.fileList3 = []
        }
      }
    },
    // 在表单打开添加时清空文件列表
    [CRUD.HOOK.beforeToAdd]() {
      this.fileList = []
    },
    handleSuccess(response, file, fileList) {
      this.crud.notify('upload success', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.form.imgPath = `${this.baseApi}/file/${response.type}/${response.realName}`
      console.log('图片路径', this.form.imgPath)
      this.form.imgName = response.realName
      // 更新文件列表
      this.fileList = [
        {
          name: response.realName,
          url: response.path
        }
      ]
    },
    handleSuccess2(response, file, fileList) {
      console.log('文件上传成功', response, file, fileList);
      
      this.crud.notify('upload success', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      const imgPath = `${this.baseApi}/file/${response.type}/${response.realName}`
      console.log('图片路径', imgPath)
      // this.form.imgName = response.realName
      // 更新文件列表
      this.fileList2.push(
        {
          name: response.realName,
          url: imgPath
        }
      )
      this.form.fileList2 = this.fileList2
    },
    removeFile1(file, fileList) {
      // console.log('文件被移除', file, fileList)
      this.fileList = fileList
    },
    removeFile2(file, fileList) {
      // console.log('文件被移除', file, fileList)
      this.fileList2 = fileList
    },
    removeFile3(file, fileList) {
      // console.log('文件被移除', file, fileList)
      this.fileList3 = fileList
    },
    handleSuccess3(response, file, fileList) {
      this.crud.notify('upload success', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      const imgPath = `${this.baseApi}/file/${response.type}/${response.realName}`
      console.log('图片路径', imgPath)
      // this.form.imgName = response.realName
      // 更新文件列表
      this.fileList3.push(
        {
          name: response.realName,
          url: imgPath
        }
      )
      this.form.fileList3 = this.fileList3
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    // 处理超出上传限制的情况，替换旧文件
    handleExceed(files, fileList) {
      // 清除旧文件
      this.$refs.upload.clearFiles()
      // 添加新文件到上传列表
      const file = files[0]
      this.$refs.upload.handleStart(file)
      // 自动上传新文件
      this.$refs.upload.submit()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
.uploadImg {
  width: 100%;
  :deep(.el-upload) {
    width: 100%;
  }
}
</style>
